package cn.yangliu.task;

import cn.yangliu.task.config.TaskProperties;
import cn.yangliu.task.entity.Task;
import cn.yangliu.task.service.TaskService;
import cn.yangliu.task.utils.AppUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;

public class TaskFactoryBean implements InitializingBean{

    @Resource
    private TaskProperties properties;

    private static final Logger logger = LoggerFactory.getLogger(TaskFactoryBean.class);
    private static Map<String,Task> taskMap = new HashMap<>();

    private static Map<String,ScheduledFuture> taskScheduledFutureMap = new HashMap<>();

    @Resource
    private TaskService taskService;
    @Override
    public void afterPropertiesSet() throws Exception {
        if (!properties.getEnableTask()){
            return;
        }
        List<Task> tasks = taskService.queryAllList();
        logger.info("初始化定时任务-->"+tasks.size());
        for (Task task : tasks) {
            createTask(task);
        }
    }

    public static void createTask(Task task){
        logger.info("创建定时任务-->"+task.getId());
        ThreadPoolTaskScheduler threadPoolTaskScheduler = AppUtils.getBean(ThreadPoolTaskScheduler.class);
        String id = task.getId();
        taskMap.put(id,task);
        ScheduledFuture<?> future = threadPoolTaskScheduler.schedule(task,new CronTrigger(task.getCron()));
        taskScheduledFutureMap.put(id,future);
    }

    public static Task getTask(String id){
        return taskMap.get(id);
    }

    public static ScheduledFuture<?> getScheduledFuture(String id){
        return taskScheduledFutureMap.get(id);
    }


    public static Task cancleTask(String id){
        logger.info("取消定时任务-->"+id);
        ScheduledFuture<?> future=taskScheduledFutureMap.get(id);
        if (future!=null){
            future.cancel(true);
        }
        taskScheduledFutureMap.remove(id);
        return taskMap.remove(id);
    }

    public static Task restartTask(Task task){
        logger.info("重启定时任务-->"+task.getId());
        Task old = cancleTask(task.getId());
        createTask(task);
       /* if (old==null){
            createTask(task);
        }else {
            old.setCron(task.getCron());
            old.setStatus(task.getStatus());
            old.setClazz(task.getClazz());
            old.setMethod(task.getMethod());
            old.setName(task.getName());
            createTask(old);
        }*/
        return old;
    }
}
